package com.jing21.learn.fs.dao;

import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.jing21.learn.common.learn.exception.ServiceException;
import com.jing21.learn.fs.config.OssClientConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.inject.Named;
import java.io.InputStream;
import java.util.Optional;

/**
 * Create By zhengjing on 2017/11/16 10:41
 */
@Named
@Slf4j
public class FileSecurityDAO {

    @Autowired
    OSSClient ossClient;

    @Autowired
    DefaultAcsClient defaultAcsClient;
    // 当前 STS API 版本
    private static final String STS_API_VERSION = "2015-04-01";

    /**
     * 主动上传文件到OSS
     *
     * @param bucket
     * @param path
     * @param inputStream
     * @return
     */
    public boolean putFile(String bucket, String path, InputStream inputStream) {
        ossClient.putObject(bucket, path, inputStream);
        return true;
    }

    /**
     * 获取临时授权 给前端 第三方
     */
    public AssumeRoleResponse.Credentials assumeRole(String roleSessionName, String policy) {

        System.err.println(policy);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setMethod(MethodType.POST);
        request.setProtocol(ProtocolType.HTTPS);
        request.setRoleArn(OssClientConfiguration.ROLE_ARN);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);
        try {

            return Optional.ofNullable(defaultAcsClient.getAcsResponse(request))
                    .map(AssumeRoleResponse::getCredentials).orElse(null);
        } catch (ClientException e) {

            log.error("获取阿里授权失败", e);
            throw new ServiceException(2000L, e.getErrMsg());
        }

    }
}
